/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.DistribuidoresVehiculos;
import com.camachosanchez.controler.jdbc.DistribuidorVehiculosJdbcControler;
import com.camachosanchez.controler.jpa.DistribuidoresVehiculosJpaController;
import com.camachosanchez.util.EstadosJDialog;
import com.camachosanchez.util.EstadosJDialog.EstadoJDialog;
import com.camachosanchez.util.GUIUtil;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;

/**
 *
 * @author Zully
 */
public class EditorDistribuidorVehiculos extends javax.swing.JDialog {

    public EstadosJDialog.EstadoJDialog Estado;
    private MaestroDistribuidoresVehiculos buscador;
    private int fila;
    private DistribuidoresVehiculos distribuidor;

    /**
     * Creates new form EditorDistribuidorVehiculos
     */
    public EditorDistribuidorVehiculos(MaestroDistribuidoresVehiculos buscador, java.awt.Frame parent, boolean modal, DistribuidoresVehiculos distribuidor, int fila) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        GUIUtil.addEscapeKey(this);
        this.buscador = buscador;
        this.fila = fila;
        if (distribuidor != null) {
            this.CargarDatosDistribuidor(distribuidor);
            this.distribuidor = distribuidor;
        }
//        else {
//            this.jCheckEstado.setSelected(true);
//        }
        this.txtNombre.requestFocusInWindow();
    }

    public EstadoJDialog getEstado() {
        return Estado;
    }

    public void setEstado(EstadoJDialog Estado) {
        switch (Estado) {
            case NUEVO:
                btnEliminar.setVisible(false);
//                jSeparator2.setVisible(false);
                break;
            case MODIFICAR:
                btnEliminar.setVisible(true);
//                jSeparator2.setVisible(true);
                break;
        }
        this.Estado = Estado;
    }

    private void GuardarDatos() {
        switch (this.Estado) {
            case NUEVO:
                this.RegistrarDistribuidor(this.LeerDatosDistribuidor());
                break;
            case MODIFICAR:
                this.ModificarDistribuidor(this.LeerDatosDistribuidor());
                break;
            case ELIMINAR:
                break;
            default:
                break;
        }
    }

    private void CargarDatosDistribuidor(DistribuidoresVehiculos distribuidor) {
//        this.jTxtCodigo.setInformacionUsuario("" + distribuidor.getId());
        this.txtNombre.setText(distribuidor.getNombre());
        this.txtDireccion.setText(distribuidor.getDireccion());
        this.txtTelefono.setText(distribuidor.getTelefono());
        this.txtFax.setText(distribuidor.getFax());
        this.txtEmail.setText(distribuidor.getCorreo());
//        this.jCheckEstado.setSelected(distribuidor.getEstado());
    }

    private DistribuidoresVehiculos LeerDatosDistribuidor() {
        DistribuidoresVehiculos d = new DistribuidoresVehiculos();
//        distribuidor.setId((this.jTxtCodigo.getText().compareTo("") != 0) ? Integer.parseInt(this.jTxtCodigo.getText()) : 0);
        d.setNombre(this.txtNombre.getText().trim());
        d.setDireccion(this.txtDireccion.getText().trim());
        d.setTelefono(this.txtTelefono.getText().trim());
        d.setFax(this.txtFax.getText().trim());
        d.setCorreo(this.txtEmail.getText().trim());
        d.setEstado(true);
        if (this.distribuidor != null) {
            d.setVehiculosList(this.distribuidor.getVehiculosList());
            d.setId(this.distribuidor.getId());
        }
        return d;
    }

    private boolean ValidarDatos() {
        if (this.txtNombre.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se requiere un nombre para el distribuidor de vehículos.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            txtNombre.requestFocusInWindow();
            return false;
        }
        return true;
    }

    private void RegistrarDistribuidor(DistribuidoresVehiculos distribuidor) {
        DistribuidoresVehiculosJpaController dao_distribuidor = new DistribuidoresVehiculosJpaController(null);
        dao_distribuidor.create(distribuidor);
        JOptionPane.showMessageDialog(this, "El distribuidor ha sido registrado correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
        buscador.llenarDistribuidores();
        this.dispose();
    }

    private void ModificarDistribuidor(DistribuidoresVehiculos distribuidor) {
        DistribuidoresVehiculosJpaController dao_distribuidor = new DistribuidoresVehiculosJpaController(null);
        try {
//            distribuidor
            dao_distribuidor.edit(distribuidor);
            JOptionPane.showMessageDialog(this, "Los datos del distribuidor han sido actualizados correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
            buscador.llenarDistribuidores();
            dispose();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlContenedor = new javax.swing.JPanel();
        toolBar = new javax.swing.JToolBar();
        jPanel2 = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        txtFax = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Distribuidor de Vehículos ::.");
        setResizable(false);

        pnlContenedor.setLayout(new java.awt.BorderLayout());

        toolBar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        toolBar.setFloatable(false);
        toolBar.setRollover(true);
        toolBar.setOpaque(false);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_save.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        jPanel2.add(btnGuardar);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_delete.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnEliminar.setFocusable(false);
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        jPanel2.add(btnEliminar);

        toolBar.add(jPanel2);

        pnlContenedor.add(toolBar, java.awt.BorderLayout.PAGE_START);

        jLabel2.setText("<html>Nombre: <font color=\"red\">(*)</font> </html>");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        jLabel3.setText("Dirección:");

        txtDireccion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDireccionKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDireccionKeyTyped(evt);
            }
        });

        jLabel4.setText("Teléfono:");

        txtTelefono.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTelefonoKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTelefonoKeyTyped(evt);
            }
        });

        txtFax.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtFaxKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtFaxKeyTyped(evt);
            }
        });

        jLabel5.setText("Fax:");

        jLabel7.setText("E-mail:");

        txtEmail.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtEmailKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtEmailKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtFax, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel2, jLabel3, jLabel4, jLabel5, jLabel7});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txtFax, txtTelefono});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtFax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pnlContenedor.add(jPanel1, java.awt.BorderLayout.CENTER);

        getContentPane().add(pnlContenedor, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // TODO add your handling code here:
        String caracteres = this.txtNombre.getText();
        if (caracteres.length() >= 100) {
            evt.consume();
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    private void txtTelefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoKeyTyped
        // TODO add your handling code here:
        String caracteres = this.txtTelefono.getText();
        if (caracteres.length() >= 20) {
            evt.consume();
        }
    }//GEN-LAST:event_txtTelefonoKeyTyped

    private void txtFaxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFaxKeyTyped
        // TODO add your handling code here:
        String caracteres = this.txtFax.getText();
        if (caracteres.length() >= 20) {
            evt.consume();
        }
    }//GEN-LAST:event_txtFaxKeyTyped

    private void txtEmailKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEmailKeyTyped
        // TODO add your handling code here:
        String caracteres = this.txtEmail.getText();
        if (caracteres.length() >= 45) {
            evt.consume();
        }
    }//GEN-LAST:event_txtEmailKeyTyped

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.txtDireccion.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtNombreKeyPressed

    private void txtDireccionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDireccionKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.txtTelefono.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtDireccionKeyPressed

    private void txtTelefonoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTelefonoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.txtFax.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtTelefonoKeyPressed

    private void txtFaxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFaxKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.txtEmail.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtFaxKeyPressed

    private void txtEmailKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEmailKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.btnGuardar.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtEmailKeyPressed

private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
// TODO add your handling code here:
    if (this.ValidarDatos()) {
        this.GuardarDatos();
    }
}//GEN-LAST:event_btnGuardarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(null, "¿Está seguro que desea eliminar este distribuidor?", "Confirmación", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            DistribuidorVehiculosJdbcControler daoJdbc = new DistribuidorVehiculosJdbcControler();
            byte estado = daoJdbc.eliminarDistribuidor(this.distribuidor.getId());
            if (estado == 1) {
                JOptionPane.showMessageDialog(this, "El distribuidor se encuentra relacionado con otros registros, no puede ser eliminado.", "Error en la eliminación", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "El distribuidor se ha eliminado de forma segura.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                buscador.borrarDistribuidor(fila);
                dispose();
            }
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtDireccionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDireccionKeyTyped
        // TODO add your handling code here:
        String caracteres = this.txtDireccion.getText();
        if (caracteres.length() >= 100) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDireccionKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel pnlContenedor;
    private javax.swing.JToolBar toolBar;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtFax;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtTelefono;
    // End of variables declaration//GEN-END:variables
}
